package com.jxs.android.ges;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.jxs.android.ges.db.CustomerHolder;
import com.jxs.android.ges.db.ManagerHolder;
import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.soap.SoapUtil;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.util.StringUtils;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.Bu_Filter_Page_List_View;
import com.jxs.android.weiget.Bu_Filter_Page_Time_View;
import com.jxs.android.weiget.TopBar;

@SuppressLint("HandlerLeak")
public class Bu_Filter_Page extends AbstractActivity {

	private Bu_Filter_Page_Time_View time_view;
	private Bu_Filter_Page_List_View cst_listView, cst_manager_lisView;

	private String startTime, endTime;
	private String cst_id;
	private String manager_id;
	private BuLoadingDailog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.bu_filter_page);
		this.initUI();
		progressDialog = new BuLoadingDailog(this);
		if (null != getIntent() && null != getIntent().getExtras()) {
			Bundle bundle = getIntent().getExtras();
			startTime = bundle.getString("startTime");
			endTime = bundle.getString("endTime");
			time_view.setStartTime(startTime);
			time_view.setEndTime(endTime);
			cst_id = bundle.getString("cst_id");
			manager_id = bundle.getString("manager_id");
			String cstName = CustomerHolder.query(cst_id);
			if (!StringUtils.isEmpety(cstName)) {
				cst_listView.setSelected(cstName);
			} else {
				cst_listView.setSelected("全部");
			}

			String managerName = ManagerHolder.query(manager_id);
			if (!StringUtils.isEmpety(managerName)) {
				cst_manager_lisView.setSelected(managerName);
			} else {
				cst_manager_lisView.setSelected("全部");
			}
			if (bundle.containsKey("hide")) {
				String hide = bundle.getString("hide");
				if ("cst".equals(hide)) {
					cst_listView.setVisibility(View.GONE);
				}
				if ("manager".equals(hide)) {
					cst_manager_lisView.setVisibility(View.GONE);
				}
			}
		}
		initData();
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		this.topBarReturn(topBar);
		topBar.setTitle("条件筛选");
		topBar.setFilterBtnText(R.string.prompt_filter);
		topBar.hindSpinnerBtn();
		topBar.setFilterBtnVisibility(View.GONE);
		topBar.showLogicBtn();
		topBar.setLogicBtnText("确定");
		topBar.setLogicBtnListern(new TopBar.LogicBtnListern() {

			@Override
			public void onClickLogicBtn() {
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				startTime = time_view.getStartTime();
				endTime = time_view.getEndTime();

				if (startTime.compareTo(endTime) > 0) {
					errorMsgPop("开始时间不能晚于结束时间！");
					return;
				}
				bundle.putString("startTime", time_view.getStartTime());
				bundle.putString("endTime", time_view.getEndTime());
				bundle.putString("cst_id", cst_id);
				bundle.putString("manager_id", manager_id);
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				finish();
			}
		});
	}

	private void initUI() {
		time_view = (Bu_Filter_Page_Time_View) findViewById(R.id.bu_filter_time);
		cst_listView = (Bu_Filter_Page_List_View) findViewById(R.id.bu_filter_cst_list);
		cst_manager_lisView = (Bu_Filter_Page_List_View) findViewById(R.id.bu_filter_cst_manager_list);
	}

	private void initData() {
		progressDialog.showLoading(R.string.load_and_wait);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getManager(GesApplication.getUserInfo().getTicket());
				String cust_manager_id = StringUtils.isEmpety(manager_id) ? "" : manager_id;
				if (cst_listView.getVisibility() != View.GONE) {
					getCustomer(GesApplication.getUserInfo().getTicket(), cust_manager_id);
				}
			}
		}).start();
	}

	/**
	 * 获取客户列表
	 * 
	 * @param ticket
	 */
	private void getManager(final String ticket) {
		String wsdl_url = GesApplication.WSDL_URL;// wsdl
		String namespace = GesApplication.WSDL_NAME_SPACE;// namespace
		// 2.4.1 getCustManagerList 【获取客户经理列表】
		String methodName = "getCustManagerList";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);
		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paserManager(response);
			}

			@Override
			public void error(String message, Exception e) {
			}

		});
	}

	private void paserManager(SoapObject soapObject) {
		List<Map<String, String>> res = new ArrayList<Map<String, String>>();
		String stauts = soapObject.getProperty("status").toString();
		if ("0".equals(stauts)) {
			SoapObject retMsgObject = (SoapObject) soapObject.getProperty("retMsg");
			if (null != retMsgObject) {
				for (int i = 0; i < retMsgObject.getPropertyCount(); i++) {
					// cust_manager_id:客户经理ID
					// cust_manager_name:客户经理名称
					SoapObject taskBeanObject = (SoapObject) retMsgObject.getProperty(i);
					Map<String, String> results = new HashMap<String, String>();
					results.put("id", SoapUtil.getValue(taskBeanObject, "cust_manager_id"));
					results.put("content", SoapUtil.getValue(taskBeanObject, "cust_manager_name"));
					res.add(results);

				}
			}
		}
		Message msg = new Message();
		msg.what = MANAGER_DATA_OVER;
		msg.obj = res;
		handler.sendMessage(msg);
	}

	private void getCustomer(final String ticket, final String cust_manager_id) {
		String wsdl_url = GesApplication.WSDL_URL;// wsdl
		String namespace = GesApplication.WSDL_NAME_SPACE;// namespace
		// 2.6.1 getCustList 【获取客户列表】
		String methodName = "getCustList";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);
		request.addProperty("cust_manager_id", cust_manager_id);
		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paserCustomer(response);
			}

			@Override
			public void error(String message, Exception e) {
			}

		});
	}

	private void paserCustomer(SoapObject soapObject) {
		List<Map<String, String>> res = new ArrayList<Map<String, String>>();
		String stauts = soapObject.getProperty("status").toString();
		if ("0".equals(stauts)) {
			SoapObject retMsgObject = (SoapObject) soapObject.getProperty("retMsg");
			if (null != retMsgObject) {
				for (int i = 0; i < retMsgObject.getPropertyCount(); i++) {
					// cust_manager_id:客户经理ID
					// cust_manager_name:客户经理名称
					SoapObject taskBeanObject = (SoapObject) retMsgObject.getProperty(i);
					Map<String, String> results = new HashMap<String, String>();
					results.put("id", SoapUtil.getValue(taskBeanObject, "cust_id"));
					results.put("content", SoapUtil.getValue(taskBeanObject, "cust_name"));
					res.add(results);
				}
			}
		}
		Message msg = new Message();
		msg.what = CUSTOMER_DATA_OVER;
		msg.obj = res;
		handler.sendMessage(msg);
	}

	static final int MANAGER_DATA_OVER = 0x1a;
	static final int CUSTOMER_DATA_OVER = 0x1b;

	private Handler handler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {

			if (!MemoryUtil.isCurrentActivity(Bu_Filter_Page.class)) {
				return;
			}

			if (msg.what == CUSTOMER_DATA_OVER) {/* 客户初始化完毕 */
				List<Map<String, String>> res = new ArrayList<Map<String, String>>();
				Map<String, String> rests = new HashMap<String, String>();
				rests.put("id", "");
				rests.put("content", "全部");
				res.add(rests);

				res.addAll((List<Map<String, String>>) msg.obj);
				cst_listView.setData(res, new Bu_Filter_Page_List_View.FiltedListItemListener() {
					@Override
					public void logic(String id, String content) {
						cst_id = id;
						cst_listView.setSelected(content);
					}
				});
				if (null != progressDialog && progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
			} else if (msg.what == MANAGER_DATA_OVER) {
				List<Map<String, String>> res = new ArrayList<Map<String, String>>();

				Map<String, String> rests = new HashMap<String, String>();
				rests.put("id", "");
				rests.put("content", "全部");
				res.add(rests);

				res.addAll((List<Map<String, String>>) msg.obj);
				cst_manager_lisView.setData(res, new Bu_Filter_Page_List_View.FiltedListItemListener() {

					@Override
					public void logic(String id, String content) {
						manager_id = id;
						cst_manager_lisView.setSelected(content);
						if (cst_listView.getVisibility() != View.GONE) {/* 如果客户列表没有隐藏 */
							progressDialog.showLoading(R.string.load_and_wait);
							new Thread(new Runnable() {
								@Override
								public void run() {
									getCustomer(GesApplication.getUserInfo().getTicket(), manager_id);
								}
							}).start();
						}
					}
				});

				if (cst_listView.getVisibility() == View.GONE) {/* 如果客户列表隐藏 */
					if (null != progressDialog && progressDialog.isShowing()) {
						progressDialog.dismiss();
					}
				}
			}
		}

	};

}
